import file from '@/api/file'
import { downLoadFile } from '@/utils/download'
import msgUtil from '@/utils/msgUtil'
import { v4 } from 'uuid';
import store from '../store';

export default {
  getFile(module, form, part){
    return file.getFiles(module,form,part)
        .catch(res => {
          msgUtil.error2('请求失败!')
        })
  },
  /**
   * 人脸 录入
   * @param file    文件本体
   * @returns {Promise<any | never>}
   */
  uploadAttenceFile(files){
    const user = localStorage.getItem('sysUser');
    const userId = JSON.parse(user).id;

    let fd = new FormData();
    fd.append('files', files);
    fd.append('userId', userId);

    return file.uploadAttenceFile(fd)
        .catch(res => {
          msgUtil.error2('请求失败!')
        })
  },
  /**
   * 上传文件
   * @param file    文件本体
   * @param formId    表单id
   * @param module    模块名
   * @param part      文件区域位置
   * @param realName   文件名字（带 后缀  ex:   jpg,pdf)
   * @returns {Promise<any | never>}
   */
  uploadFile(files,formId,module,part,realName){
    const user = localStorage.getItem('sysUser');

    const company = localStorage.getItem('sysCompany');
    const companyId = (company && company != 'null') ? JSON.parse(company).id:'';
    const userId = JSON.parse(user).id;
    let fd = new FormData();
    fd.append('files', files);
    fd.append('form', formId);
    fd.append('module', module);
    fd.append('part', part);
    fd.append('createrId', userId);
    fd.append('createrComId', companyId);
    const uploading = store.state.upload.uploading || [];
    const uid = files.uid || v4();
    uploading.push({ name: files.name, uid });
    store.dispatch('upload/update_uploading', uploading);
    const callback = () => {
      const arr = store.state.upload.uploading || [];
      const newArr = arr.filter((a) => a.uid !== uid);
      store.dispatch('upload/update_uploading', newArr);
    }
    return file.uploadFile(fd).then((res) => {
      callback();
      return res;
    }).catch(res => {
      callback();
      msgUtil.error2('请求失败!')
    })
  },

  /**
   *解绑
   * @param fileId  表单id
   * @returns {Promise<any | never>}
   */
  removeFile(fileId){
    return file.deleteFile(fileId).then(res=>{
      return new Promise(resolve => {
        resolve(res)
      })
    }).catch(res => {
      msgUtil.error2('请求失败!')
    })

  },

  // preView(fieldId) {
  //   return file.download(fieldId).then(res => {
  //     var blob = new Blob([res],
  //       {
  //         type: 'application/octet-stream;charset=UTF-8'
  //       });
  //     window.URL.createObjectURL(blob);
  //     return new Promise(function (resolve,reject) {
  //       resolve(res)
  //     })
  //   })
  //   .catch(res=>{
  //     console.log(res)
  //     // Vue.prototype.$messageError('请求失败!')
  //   })
  // },
  preView(fieldId) {
    // return file.download(fieldId).then(res => {
    //   var blob = new Blob([res],
    //     {
    //       type: 'application/octet-stream;charset=UTF-8'
    //     });
    //   return window.URL.createObjectURL(blob);
    // })
    file.preview(fieldId).then(response => {
      window.open(response.data)
    })
  },

  /**
   *
   * @param fileId   表单id
   * @returns {Promise<any | never>}
   */
  checkFile(fieldId, fileName){
    return  file.download(fieldId).then(res => {
      var blob = new Blob([res],
          {
            type: 'application/octet-stream;charset=UTF-8'
          });
      var downloadElement = document.createElement('a');
      var href = window.URL.createObjectURL(blob); //创建下载的链接
      downloadElement.style.display = 'none';
      downloadElement.href = href;
      downloadElement.download = decodeURI(fileName); //下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); //点击下载
      document.body.removeChild(downloadElement); //下载完成移除元素
      window.URL.revokeObjectURL(href); //释放掉blob对象
      return new Promise(resolve => {
        resolve(res)
      })
    })
  },
  checkFileForPreview (fieldId) {
    return new Promise((resolve, reject) => {
      file.download(fieldId).then(res => {
        const blob = new Blob([res],
            {
              type: 'application/octet-stream;charset=UTF-8'
            });
        const href = window.URL.createObjectURL(blob); //创建下载的链接
        resolve({
          href,
          destroy () {
            window.URL.revokeObjectURL(href)
          }
        })
      }).catch(() => {
        reject(...arguments)
      })
    })
  },

  /**
   * 表单提交更新form
   * @param {*} oldId
   * @param {*} newId
   */
  updateForm(oldId, newId) {
    file.updateForm(oldId, newId)
  },
  changeBind(fileId,module,form,part){
    file.changeBind(fileId,module,form,part)
  }
}
